<?php
declare (strict_types = 1);

namespace app\admin\controller;

use think\Db;
use think\Session;
use app\admin\model\AdminUser;
use app\admin\model\Role;
use app\admin\model\Permission;
use app\admin\model\UserRole;
use app\admin\model\RolePermission;
use app\admin\model\SystemConfig;
use app\admin\service\OperationLogService;

/**
 * Settings控制器 - 用于兼容旧的前端路由
 * 实际功能委托给Admin控制器
 * Class Settings
 * @package app\admin\controller
 */
class Settings extends BaseController
{
    /**
     * 管理员管理页面
     */
    public function users()
    {
        $this->assign('current_page', 'settings');
        $this->assign('current_subpage', 'user_manage');
        return view();
    }
    
    /**
     * 获取用户列表（AJAX）
     */
    public function getUserList()
    {
        try {
            $page = $this->request->param('page', 1);
            $limit = $this->request->param('limit', 10);
            $username = $this->request->param('username', '');
            $real_name = $this->request->param('real_name', '');
            $status = $this->request->param('status', '');
            
            $where = ['is_deleted' => 0]; // 只查询未删除的用户
            if ($username) {
                $where['username'] = ['like', '%' . $username . '%'];
            }
            if ($real_name) {
                $where['real_name'] = ['like', '%' . $real_name . '%'];
            }
            if ($status !== '') {
                $where['status'] = $status;
            }
            
            // 不使用关联查询，避免表不存在的问题
            $users = AdminUser::where($where)
                ->page($page, $limit)
                ->select();
            
            $total = AdminUser::where($where)->count();
            
            $data = [];
            foreach ($users as $user) {
                // 尝试获取角色信息
                $roleName = '-';
                try {
                    if (isset($user->role_id) && $user->role_id) {
                        $role = Role::find($user->role_id);
                        if ($role) {
                            $roleName = $role->role_name;
                        }
                    }
                } catch (\Exception $e) {
                    // 角色表不存在或查询失败，使用默认值
                }
                
                $data[] = [
                    'id' => $user->id,
                    'username' => $user->username,
                    'real_name' => $user->real_name ?? '-',
                    'email' => $user->email ?? '-',
                    'phone' => $user->phone ?? '-',
                    'department' => $user->department ?? '-',
                    'position' => $user->position ?? '-',
                    'role_names' => $roleName,
                    'status' => $user->status,
                    'last_login_time' => $user->last_login_time ?? '-',
                    'created_at' => $user->created_at ?? '-'
                ];
            }
            
            return json(['code' => 0, 'msg' => '', 'count' => $total, 'data' => $data]);
        } catch (\Exception $e) {
            return json(['code' => 1, 'msg' => '查询失败：' . $e->getMessage(), 'count' => 0, 'data' => []]);
        }
    }

    /**
     * 角色管理页面
     */
    public function roles()
    {
        try {
            // 获取所有权限用于分配
            $permissions = Permission::where('status', 1)->order('sort_order asc')->select();
            $this->assign('permissions', $permissions);
        } catch (\Exception $e) {
            // 权限表不存在，使用空数组
            $this->assign('permissions', []);
        }
        
        $this->assign('current_page', 'settings');
        $this->assign('current_subpage', 'role_manage');
        return view();
    }
    
    /**
     * 获取角色列表（AJAX）
     */
    public function getRoleList()
    {
        try {
            $page = $this->request->param('page', 1);
            $limit = $this->request->param('limit', 10);
            $role_name = $this->request->param('role_name', '');
            $status = $this->request->param('status', '');
            
            $where = [];
            if ($role_name) {
                $where['role_name'] = ['like', '%' . $role_name . '%'];
            }
            if ($status !== '') {
                $where['status'] = $status;
            }
            
            $roles = Role::where($where)
                ->page($page, $limit)
                ->select();
            
            $total = Role::where($where)->count();
            
            $data = [];
            foreach ($roles as $role) {
                // 获取角色的权限数量
                $permissionCount = 0;
                try {
                    $permissionCount = RolePermission::where('role_id', $role->id)->count();
                } catch (\Exception $e) {
                    // 权限关联表不存在
                }
                
                $data[] = [
                    'id' => $role->id,
                    'role_name' => $role->role_name ?? '-',
                    'role_code' => $role->role_code ?? '-',
                    'description' => $role->description ?? '-',
                    'permission_count' => $permissionCount,
                    'status' => $role->status ?? 1,
                    'created_at' => $role->created_at ?? '-'
                ];
            }
            
            return json(['code' => 0, 'msg' => '', 'count' => $total, 'data' => $data]);
        } catch (\Exception $e) {
            return json(['code' => 1, 'msg' => '查询失败：' . $e->getMessage(), 'count' => 0, 'data' => []]);
        }
    }

    /**
     * 权限管理页面
     */
    public function permissions()
    {
        $this->assign('current_page', 'settings');
        $this->assign('current_subpage', 'permission_manage');
        return view();
    }
    
    /**
     * 获取权限列表（AJAX）
     */
    public function getPermissionList()
    {
        try {
            $page = $this->request->param('page', 1);
            $limit = $this->request->param('limit', 10);
            $permission_name = $this->request->param('permission_name', '');
            $is_menu = $this->request->param('is_menu', '');
            
            $where = [];
            if ($permission_name) {
                $where['permission_name'] = ['like', '%' . $permission_name . '%'];
            }
            if ($is_menu !== '') {
                $where['is_menu'] = $is_menu;
            }
            
            $permissions = Permission::where($where)
                ->order('sort_order asc')
                ->page($page, $limit)
                ->select();
            
            $total = Permission::where($where)->count();
            
            $data = [];
            foreach ($permissions as $permission) {
                $data[] = [
                    'id' => $permission->id,
                    'permission_name' => $permission->permission_name ?? '-',
                    'permission_code' => $permission->permission_code ?? '-',
                    'description' => $permission->description ?? '-',
                    'is_menu' => $permission->is_menu ?? 0,
                    'menu_url' => $permission->menu_url ?? '-',
                    'status' => $permission->status ?? 1,
                    'sort_order' => $permission->sort_order ?? 0,
                    'created_at' => $permission->created_at ?? '-'
                ];
            }
            
            return json(['code' => 0, 'msg' => '', 'count' => $total, 'data' => $data]);
        } catch (\Exception $e) {
            return json(['code' => 1, 'msg' => '查询失败：' . $e->getMessage(), 'count' => 0, 'data' => []]);
        }
    }
    
    /**
     * 获取所有角色（AJAX）
     */
    public function getAllRoles()
    {
        try {
            $roles = Role::where('status', 1)->select();
            return json(['code' => 0, 'msg' => '', 'data' => $roles]);
        } catch (\Exception $e) {
            return json(['code' => 1, 'msg' => '查询失败：' . $e->getMessage(), 'data' => []]);
        }
    }
    
    /**
     * 添加用户（AJAX）
     */
    public function addUser()
    {
        $result = (new Admin())->add();
        
        // 记录操作日志
        if (is_array($result)) {
            $resultArray = json_decode(json_encode($result), true);
            if (isset($resultArray['code']) && $resultArray['code'] == 0) {
                $username = $this->request->param('username', '');
                $this->logDataChange('添加', '用户', $username, $this->request->param());
            }
        }
        
        return $result;
    }
    
    /**
     * 编辑用户（AJAX）
     */
    public function editUser()
    {
        $userId = $this->request->param('id', 0);
        $result = (new Admin())->edit();
        
        // 记录操作日志
        if (is_array($result)) {
            $resultArray = json_decode(json_encode($result), true);
            if (isset($resultArray['code']) && $resultArray['code'] == 0) {
                $this->logDataChange('编辑', '用户', $userId, $this->request->param());
            }
        }
        
        return $result;
    }
    
    /**
     * 删除用户（AJAX）
     */
    public function deleteUser()
    {
        $userId = $this->request->param('id', 0);
        $result = (new Admin())->delete();
        
        // 记录操作日志
        if (is_array($result)) {
            $resultArray = json_decode(json_encode($result), true);
            if (isset($resultArray['code']) && $resultArray['code'] == 0) {
                $this->logDataChange('删除', '用户', $userId, ['id' => $userId]);
            }
        }
        
        return $result;
    }
    
    /**
     * 重置密码（AJAX）
     */
    public function resetPassword()
    {
        $id = $this->request->param('id', 0);
        $newPassword = $this->request->param('password', '123456');
        
        $user = AdminUser::find($id);
        if (!$user) {
            return json(['code' => 404, 'msg' => '用户不存在']);
        }
        
        $user->password = md5($newPassword);
        if ($user->save()) {
            // 记录操作日志
            $this->log('重置密码', "重置用户 {$user->username} 的密码");
            return json(['code' => 0, 'msg' => '密码重置成功']);
        }
        
        return json(['code' => 400, 'msg' => '密码重置失败']);
    }
    
    /**
     * 添加角色（AJAX）
     */
    public function addRole()
    {
        $result = (new Admin())->addRole();
        
        // 记录操作日志
        if (is_array($result)) {
            $resultArray = json_decode(json_encode($result), true);
            if (isset($resultArray['code']) && $resultArray['code'] == 0) {
                $roleName = $this->request->param('role_name', '');
                $this->logDataChange('添加', '角色', $roleName, $this->request->param());
            }
        }
        
        return $result;
    }
    
    /**
     * 编辑角色（AJAX）
     */
    public function editRole()
    {
        $roleId = $this->request->param('id', 0);
        $result = (new Admin())->editRole();
        
        // 记录操作日志
        if (is_array($result)) {
            $resultArray = json_decode(json_encode($result), true);
            if (isset($resultArray['code']) && $resultArray['code'] == 0) {
                $this->logDataChange('编辑', '角色', $roleId, $this->request->param());
            }
        }
        
        return $result;
    }
    
    /**
     * 删除角色（AJAX）
     */
    public function deleteRole()
    {
        $roleId = $this->request->param('id', 0);
        $result = (new Admin())->deleteRole();
        
        // 记录操作日志
        if (is_array($result)) {
            $resultArray = json_decode(json_encode($result), true);
            if (isset($resultArray['code']) && $resultArray['code'] == 0) {
                $this->logDataChange('删除', '角色', $roleId, ['id' => $roleId]);
            }
        }
        
        return $result;
    }
    
    /**
     * 分配权限
     */
    public function assignPermissions()
    {
        $roleId = $this->request->param('role_id', 0);
        $result = (new Admin())->assignPermissions();
        
        // 记录操作日志
        if (is_array($result)) {
            $resultArray = json_decode(json_encode($result), true);
            if (isset($resultArray['code']) && $resultArray['code'] == 0) {
                $permissionIds = $this->request->param('permission_ids', []);
                $this->log('分配权限', "为角色ID {$roleId} 分配 " . count($permissionIds) . " 个权限");
            }
        }
        
        return $result;
    }
    
    /**
     * 获取角色权限（AJAX）
     */
    public function getRolePermissions()
    {
        try {
            $roleId = $this->request->param('role_id', 0);
            $permissions = RolePermission::where('role_id', $roleId)->column('permission_id');
            return json(['code' => 0, 'msg' => '', 'data' => $permissions]);
        } catch (\Exception $e) {
            return json(['code' => 1, 'msg' => '查询失败：' . $e->getMessage(), 'data' => []]);
        }
    }
    
    /**
     * 获取用户详情（AJAX）
     */
    public function getUserDetail()
    {
        try {
            $id = $this->request->param('id', 0);
            $user = AdminUser::where('id', $id)->where('is_deleted', 0)->find();
            
            if (!$user) {
                return json(['code' => 1, 'msg' => '用户不存在或已被删除']);
            }
            
            // 获取用户的角色ID列表
            $roleIds = UserRole::where('user_id', $id)->column('role_id');
            $user->role_ids = $roleIds;
            
            return json(['code' => 0, 'msg' => '', 'data' => $user]);
        } catch (\Exception $e) {
            return json(['code' => 1, 'msg' => '查询失败：' . $e->getMessage()]);
        }
    }
    
    /**
     * 获取角色详情（AJAX）
     */
    public function getRoleDetail()
    {
        try {
            $id = $this->request->param('id', 0);
            $role = Role::find($id);
            
            if (!$role) {
                return json(['code' => 1, 'msg' => '角色不存在']);
            }
            
            return json(['code' => 0, 'msg' => '', 'data' => $role]);
        } catch (\Exception $e) {
            return json(['code' => 1, 'msg' => '查询失败：' . $e->getMessage()]);
        }
    }
    
    /**
     * 获取权限详情（AJAX）
     */
    public function getPermissionDetail()
    {
        try {
            $id = $this->request->param('id', 0);
            $permission = Permission::find($id);
            
            if (!$permission) {
                return json(['code' => 1, 'msg' => '权限不存在']);
            }
            
            return json(['code' => 0, 'msg' => '', 'data' => $permission]);
        } catch (\Exception $e) {
            return json(['code' => 1, 'msg' => '查询失败：' . $e->getMessage()]);
        }
    }
    
    /**
     * 获取权限树（AJAX）
     */
    public function getPermissionTree()
    {
        try {
            $permissions = Permission::where('status', 1)
                ->order('sort_order', 'asc')
                ->select();
            
            // 构建树形结构
            $tree = $this->buildPermissionTree($permissions);
            
            return json(['code' => 0, 'msg' => '', 'data' => $tree]);
        } catch (\Exception $e) {
            return json(['code' => 1, 'msg' => '查询失败：' . $e->getMessage(), 'data' => []]);
        }
    }
    
    /**
     * 构建权限树
     */
    private function buildPermissionTree($permissions, $parentId = 0)
    {
        $tree = [];
        foreach ($permissions as $permission) {
            if ($permission->parent_id == $parentId) {
                $node = [
                    'id' => $permission->id,
                    'title' => $permission->permission_name,
                    'value' => $permission->id,
                    'spread' => true,
                    'children' => $this->buildPermissionTree($permissions, $permission->id)
                ];
                $tree[] = $node;
            }
        }
        return $tree;
    }
    
    /**
     * 添加权限（AJAX）
     */
    public function addPermission()
    {
        try {
            $data = $this->request->param();
            $permission = new Permission();
            $permission->permission_name = $data['permission_name'] ?? '';
            $permission->permission_code = $data['permission_code'] ?? '';
            $permission->parent_id = $data['parent_id'] ?? 0;
            $permission->is_menu = $data['is_menu'] ?? 0;
            $permission->menu_url = $data['menu_url'] ?? '';
            $permission->menu_icon = $data['menu_icon'] ?? '';
            $permission->sort_order = $data['sort_order'] ?? 0;
            $permission->status = $data['status'] ?? 1;
            
            if ($permission->save()) {
                // 记录操作日志
                $this->logDataChange('添加', '权限', $permission->permission_name, $data);
                return json(['code' => 0, 'msg' => '添加成功']);
            }
            
            return json(['code' => 1, 'msg' => '添加失败']);
        } catch (\Exception $e) {
            return json(['code' => 1, 'msg' => '添加失败：' . $e->getMessage()]);
        }
    }
    
    /**
     * 编辑权限（AJAX）
     */
    public function editPermission()
    {
        try {
            $data = $this->request->param();
            $id = $data['id'] ?? 0;
            
            $permission = Permission::find($id);
            if (!$permission) {
                return json(['code' => 1, 'msg' => '权限不存在']);
            }
            
            $permission->permission_name = $data['permission_name'] ?? $permission->permission_name;
            $permission->permission_code = $data['permission_code'] ?? $permission->permission_code;
            $permission->parent_id = $data['parent_id'] ?? $permission->parent_id;
            $permission->is_menu = $data['is_menu'] ?? $permission->is_menu;
            $permission->menu_url = $data['menu_url'] ?? $permission->menu_url;
            $permission->menu_icon = $data['menu_icon'] ?? $permission->menu_icon;
            $permission->sort_order = $data['sort_order'] ?? $permission->sort_order;
            $permission->status = $data['status'] ?? $permission->status;
            
            if ($permission->save()) {
                // 记录操作日志
                $this->logDataChange('编辑', '权限', $id, $data);
                return json(['code' => 0, 'msg' => '更新成功']);
            }
            
            return json(['code' => 1, 'msg' => '更新失败']);
        } catch (\Exception $e) {
            return json(['code' => 1, 'msg' => '更新失败：' . $e->getMessage()]);
        }
    }
    
    /**
     * 删除权限（AJAX）
     */
    public function deletePermission()
    {
        try {
            $id = $this->request->param('id', 0);
            
            // 检查是否有子权限
            $hasChildren = Permission::where('parent_id', $id)->count();
            if ($hasChildren > 0) {
                return json(['code' => 1, 'msg' => '该权限下有子权限，无法删除']);
            }
            
            // 检查是否有角色在使用
            $hasRoles = RolePermission::where('permission_id', $id)->count();
            if ($hasRoles > 0) {
                return json(['code' => 1, 'msg' => '该权限已分配给角色，无法删除']);
            }
            
            $permission = Permission::find($id);
            if (!$permission) {
                return json(['code' => 1, 'msg' => '权限不存在']);
            }
            
            if ($permission->delete()) {
                // 记录操作日志
                $this->logDataChange('删除', '权限', $id, ['id' => $id, 'name' => $permission->permission_name]);
                return json(['code' => 0, 'msg' => '删除成功']);
            }
            
            return json(['code' => 1, 'msg' => '删除失败']);
        } catch (\Exception $e) {
            return json(['code' => 1, 'msg' => '删除失败：' . $e->getMessage()]);
        }
    }
    
    /**
     * 操作日志
     */
    public function logs()
    {
        $this->assign('current_page', 'settings');
        $this->assign('current_subpage', 'log_view');
        return view();
    }
    
    /**
     * 获取操作日志列表（AJAX）
     */
    public function getLogsList()
    {
        try {
            $page = $this->request->param('page', 1);
            $limit = $this->request->param('limit', 10);
            $search = $this->request->param('search', '');
            $module = $this->request->param('module', '');
            $action = $this->request->param('action', '');
            $level = $this->request->param('level', '');

            $where = [];
            if ($search) {
                $where['username|description'] = ['like', '%' . $search . '%'];
            }
            if ($module) {
                $where['module'] = $module;
            }
            if ($action) {
                $where['action'] = $action;
            }
            if ($level) {
                $where['level'] = $level;
            }
            
            $total = Db::table('sys_log')->where($where)->count();
            $logs = Db::table('sys_log')
                ->where($where)
                ->order('id', 'desc')
                ->page($page, $limit)
                ->select();
            
            return json(['code' => 0, 'msg' => '', 'count' => $total, 'data' => $logs]);
        } catch (\Exception $e) {
            return json(['code' => 1, 'msg' => '查询失败：' . $e->getMessage(), 'count' => 0, 'data' => []]);
        }
    }
    
    /**
     * 个人资料
     */
    public function profile()
    {
        $userId = Session::get('admin_id');
        $user = AdminUser::find($userId);
        
        if ($this->request->isPost()) {
            $data = $this->request->param();
            $user->real_name = $data['real_name'] ?? $user->real_name;
            $user->phone = $data['phone'] ?? $user->phone;
            $user->email = $data['email'] ?? $user->email;
            
            if ($user->save()) {
                return json(['code' => 200, 'msg' => '更新成功']);
            }
            
            return json(['code' => 400, 'msg' => '更新失败']);
        }
        
        $this->assign('user', $user);
        $this->assign('current_page', 'settings');
        $this->assign('current_subpage', 'profile_manage');
        return view();
    }
    
    /**
     * 获取个人资料（AJAX）
     */
    public function getProfile()
    {
        try {
            $userId = Session::get('admin_id');
            $user = AdminUser::find($userId);
            
            if (!$user) {
                return json(['code' => 1, 'msg' => '用户不存在']);
            }
            
            // 获取用户角色
            $roleIds = UserRole::where('user_id', $userId)->column('role_id');
            $roles = [];
            if ($roleIds) {
                $roles = Role::whereIn('id', $roleIds)->select();
            }
            
            return json([
                'code' => 0,
                'msg' => '获取成功',
                'data' => [
                    'id' => $user->id,
                    'username' => $user->username,
                    'real_name' => $user->real_name ?? '',
                    'email' => $user->email ?? '',
                    'phone' => $user->phone ?? '',
                    'department' => $user->department ?? '',
                    'position' => $user->position ?? '',
                    'avatar' => $user->avatar ?? '',
                    'last_login_time' => $user->last_login_time ?? '',
                    'created_at' => $user->created_at ?? '',
                    'roles' => $roles
                ]
            ]);
        } catch (\Exception $e) {
            return json(['code' => 1, 'msg' => '获取失败：' . $e->getMessage()]);
        }
    }
    
    /**
     * 更新个人资料（AJAX）
     */
    public function updateProfile()
    {
        try {
            $userId = Session::get('admin_id');
            $user = AdminUser::find($userId);
            
            if (!$user) {
                return json(['code' => 1, 'msg' => '用户不存在']);
            }
            
            $data = $this->request->param();
            $user->real_name = $data['real_name'] ?? $user->real_name;
            $user->phone = $data['phone'] ?? $user->phone;
            $user->email = $data['email'] ?? $user->email;
            $user->department = $data['department'] ?? $user->department;
            $user->position = $data['position'] ?? $user->position;
            
            if ($user->save()) {
                return json(['code' => 0, 'msg' => '更新成功']);
            }
            
            return json(['code' => 1, 'msg' => '更新失败']);
        } catch (\Exception $e) {
            return json(['code' => 1, 'msg' => '更新失败：' . $e->getMessage()]);
        }
    }
    
    /**
     * 上传头像（AJAX）
     */
    public function uploadAvatar()
    {
        try {
            $userId = Session::get('admin_id');
            $user = AdminUser::find($userId);
            
            if (!$user) {
                return json(['code' => 1, 'msg' => '用户不存在', 'message' => '用户不存在']);
            }
            
            // 获取上传的文件
            $file = $this->request->file('avatar');
            
            if (!$file) {
                return json(['code' => 1, 'msg' => '请选择要上传的文件', 'message' => '请选择要上传的文件']);
            }
            
            // 使用UploadService上传头像
            $result = \app\admin\service\UploadService::uploadAvatar($file, $userId);
            
            if ($result['code'] === 0) {
                // 删除旧头像（如果存在）
                if ($user->avatar && $user->avatar !== '/static/images/default-avatar.png') {
                    // 移除开头的斜杠，因为deleteFile方法会自动添加web路径
                    $oldPath = ltrim($user->avatar, '/');
                    \app\admin\service\UploadService::deleteFile($oldPath);
                }
                
                // 更新用户头像
                $user->avatar = $result['data']['url'];
                $user->save();
                
                // 更新会话中的头像信息
                Session::set('admin_info.avatar', $result['data']['url']);
                
                // 记录日志
                try {
                    OperationLogService::log('上传头像', '操作事件', '上传新头像', ['user_id' => $userId]);
                } catch (\Exception $e) {
                    // 日志失败不影响主流程
                }
                
                return json([
                    'code' => 0,
                    'msg' => '头像上传成功',
                    'message' => '头像上传成功',
                    'data' => [
                        'url' => $result['data']['url'],
                        'thumb' => $result['data']['thumb'] ?? $result['data']['url']
                    ]
                ]);
            }
            
            return json(['code' => 1, 'msg' => $result['msg'], 'message' => $result['msg']]);
            
        } catch (\Exception $e) {
            return json(['code' => 1, 'msg' => '上传失败：' . $e->getMessage(), 'message' => '上传失败：' . $e->getMessage()]);
        }
    }
    
    /**
     * 修改密码页面
     */
    public function changePassword()
    {
        $this->assign('current_page', 'settings');
        $this->assign('current_subpage', 'password_change');
        return view();
    }
    
    /**
     * 更新密码（AJAX）
     */
    public function updatePassword()
    {
        if (!$this->request->isPost()) {
            return json(['code' => 1, 'msg' => '请求方式错误']);
        }
        
        $userId = Session::get('admin_id');
        $oldPassword = $this->request->param('old_password', '');
        $newPassword = $this->request->param('new_password', '');
        $confirmPassword = $this->request->param('confirm_password', '');
        
        if (empty($oldPassword) || empty($newPassword) || empty($confirmPassword)) {
            return json(['code' => 1, 'msg' => '请填写完整信息']);
        }
        
        if ($newPassword !== $confirmPassword) {
            return json(['code' => 1, 'msg' => '两次密码输入不一致']);
        }
        
        try {
            $user = AdminUser::find($userId);
            if (!$user) {
                return json(['code' => 1, 'msg' => '用户不存在']);
            }
            
            if ($user->password !== md5($oldPassword)) {
                return json(['code' => 1, 'msg' => '原密码错误']);
            }
            
            // 直接更新密码，不使用模型修改器（避免二次加密）
            $updateResult = AdminUser::where('id', $userId)->update(['password' => md5($newPassword)]);
            if ($updateResult) {
                // 记录操作日志
                try {
                    OperationLogService::addLog('修改密码', '成功修改登录密码');
                } catch (\Exception $e) {
                    // 日志记录失败不影响密码修改
                }
                
                return json(['code' => 0, 'msg' => '密码修改成功，请重新登录']);
            }
            
            return json(['code' => 1, 'msg' => '密码修改失败']);
        } catch (\Exception $e) {
            return json(['code' => 1, 'msg' => '修改失败：' . $e->getMessage()]);
        }
    }
}

